package com.besall.allbase.view.activity.chipstoollevel4.protocol.Settings;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import androidx.cardview.widget.CardView;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.lib.devices.sgsettingentity.setting.PanelModel;
import bb.lanxing.lib.devices.sgsettingentity.setting.PanelSportMode;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.ui.GsonUtils;
import bb.lanxing.utils.PanelModelToJsonUtil;
import com.bes.sdk.utils.SettingsJsonUtils;
import com.besall.allbase.common.utils.FileUtils;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.view.listener.OnButtonClickListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class DeviceProfiles1Activity extends BaseActivity {
	private static final String TAG = "SettingsActivity";
	private static final int REQUEST_CODE_TARGET = 4283;

	private static final String DEFAULT_PANEL_JSON_STR = "[{\"target\":[0,0],\"remind\":[0,0,0,60,90,130,40]," + "\"autopause\":1,\"autolap\":[0,0,0],\"manuallap\":[0,0]," + "\"displayData\":[{\"panelId\":6,\"items\":[101,201,301,401,501,601,0,0]}," + "{\"panelId\":4,\"items\":[701,302,503,402,0,0,0,0]}]}," + "{\"target\":[0,0],\"remind\":[0,0,0,60,90,130,40]," + "\"autopause\":1,\"autolap\":[0,0,0],\"manuallap\":[0,0]," + "\"displayData\":[{\"panelId\":3,\"items\":[205,701,206,0,0,0,0,0]}," + "{\"panelId\":2,\"items\":[301,701,0,0,0,0,0,0]}]}," + "{\"target\":[0,0],\"remind\":[0,0,0,60,90,130,40]," + "\"autopause\":1,\"autolap\":[0,0,0],\"manuallap\":[0,0]," + "\"displayData\":[{\"panelId\":4,\"items\":[601,801,901,701,0,0,0,0]}," + "{\"panelId\":5,\"items\":[402,403,701,501,503,0,0,0]}]}," + "{\"target\":[0,0],\"remind\":[0,0,0,60,90,130,40]," + "\"autopause\":1,\"autolap\":[0,0,0],\"manuallap\":[0,0]," + "\"displayData\":[{\"panelId\":3,\"items\":[201,202,701,0,0,0,0,0]}," + "{\"panelId\":6,\"items\":[101,205,301,302,601,701,0,0]}]}," + "{\"target\":[0,0],\"remind\":[0,0,0,60,90,130,40]," + "\"autopause\":0,\"autolap\":[0,0,0],\"manuallap\":[0,0]," + "\"displayData\":[{\"panelId\":5,\"items\":[901,1101,301,303,701,0,0,0]}," + "{\"panelId\":1,\"items\":[701,0,0,0,0,0,0,0]}]}]";

	private TextView targetValue;

	private Switch autoPauseSwitch;

	private TextView autoLapValue;
	private Switch autoLapSwitch;

	private TextView manualLapValue;
	private Switch manualLapSwitch;

	private String device_model = "BC270";
	private String sn = "test";
	private PanelModel PANEL_MODEL;
	private PanelSportMode panelSportMode;

	private int sportMode;

	@Override public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_device_profiles1);

		ImageView back = findViewById(R.id.back);
		back.setOnClickListener(v -> onBackPressed());

		TextView title = findViewById(R.id.title);
		title.setText(getIntent().getStringExtra("title"));

		sportMode = getIntent().getIntExtra("sportMode", 0);

		CardView target = findViewById(R.id.target);
		target.setOnClickListener(v -> {
			Intent intent = new Intent(this, DeviceTargetActivity.class);
			intent.putExtra("sportMode", sportMode);
			intent.putExtra("title", getIntent().getStringExtra("title") + " " + getString(R.string.device_profiles_setting_detail_target));
			intent.putExtra("PANEL_MODEL", PanelModelToJsonUtil.toJson(PANEL_MODEL));
			startActivityForResult(intent, REQUEST_CODE_TARGET);
		});
		targetValue = findViewById(R.id.targetValue);

		CardView reminder = findViewById(R.id.reminder);
		reminder.setOnClickListener(v -> {
			Intent intent = new Intent(this, DeviceRemindActivity.class);
			intent.putExtra("sportMode", sportMode);
			intent.putExtra("title", getIntent().getStringExtra("title"));
			intent.putExtra("PANEL_MODEL", PanelModelToJsonUtil.toJson(PANEL_MODEL));
			startActivityForResult(intent, REQUEST_CODE_TARGET);
		});

		autoPauseSwitch = findViewById(R.id.autoPauseSwitch);
		autoPauseSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
			if (isChecked) {
				panelSportMode.setAutopause(1);
			} else {
				panelSportMode.setAutopause(0);
			}
		});

		CardView panelDisplay = findViewById(R.id.panelDisplay);
		panelDisplay.setOnClickListener(v -> {
			Intent intent = new Intent(this, DevicePanelDisplayActivity.class);
			intent.putExtra("sportMode", sportMode);
			intent.putExtra("title", getIntent().getStringExtra("title") + " " + getString(R.string.device_profiles_setting_detail_panel_display));
			intent.putExtra("PANEL_MODEL", PanelModelToJsonUtil.toJson(PANEL_MODEL));
			startActivityForResult(intent, REQUEST_CODE_TARGET);
		});

		LinearLayout autoLapLayout = findViewById(R.id.autoLapLayout);
		autoLapLayout.setOnClickListener(v -> {
			Intent intent = new Intent(this, DeviceAutoLapActivity.class);
			intent.putExtra("sportMode", sportMode);
			intent.putExtra("title", getIntent().getStringExtra("title") + " " + getString(R.string.device_profiles_setting_detail_auto_lap));
			intent.putExtra("PANEL_MODEL", PanelModelToJsonUtil.toJson(PANEL_MODEL));
			startActivityForResult(intent, REQUEST_CODE_TARGET);
		});
		autoLapValue = findViewById(R.id.autoLapValue);
		autoLapSwitch = findViewById(R.id.autoLapSwitch);
		autoLapSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
			if (isChecked) {
				panelSportMode.getAutolap().set(0, 1);
			} else {
				panelSportMode.getAutolap().set(0, 0);
			}
		});

		LinearLayout manualLapLayout = findViewById(R.id.manualLapLayout);
		String[] bbsTypesName = {
			getString(R.string.device_profiles_setting_detail_lap_mode_time), getString(R.string.device_profiles_setting_detail_lap_mode_distance), getString(R.string.device_profiles_setting_detail_lap_mode_calories), getString(R.string.device_profiles_setting_detail_lap_mode_location)
		};
		manualLapLayout.setOnClickListener(v -> {
			new CircleDialog.Builder().setItems(bbsTypesName, (parent, view, position, id) -> {
				panelSportMode.getManuallap().set(1, position);
				updateData();
				return true;
			}).show(getSupportFragmentManager());
		});
		manualLapValue = findViewById(R.id.manualLapValue);
		manualLapSwitch = findViewById(R.id.manualLapSwitch);
		manualLapSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
			if (isChecked) {
				panelSportMode.getManuallap().set(0, 1);
			} else {
				panelSportMode.getManuallap().set(0, 0);
			}
		});

		CardView reset_data = findViewById(R.id.reset_data);
		reset_data.setOnClickListener(v1 -> {
			new CircleDialog.Builder().setTitle(getString(R.string.device_profiles_setting_detail_reset_data)).setText(getString(R.string.device_profiles_setting_reset)).setPositive(getString(R.string.confirm), v -> {
				restoreContentToFileDefault();
				return true;
			}).setNegative(getString(R.string.cancel), (OnButtonClickListener) null).show(getSupportFragmentManager());
		});

		parseFile();
	}

	private void parseFile() {
		device_model = SettingsJsonUtils.getDeviceModel(this);
		sn = SettingsJsonUtils.getSn(this);
		String devicePanelFolderPath = FileUtils.checkExternalDirectoryPathExist(false, device_model, sn, SettingsJsonUtils.SETTINGS);
		File profileFile = new File(devicePanelFolderPath, SettingsJsonUtils.PANEL_JSON);

		if (profileFile.exists()) {
			BufferedReader bufferedReader = null;
			try {
				bufferedReader = new BufferedReader(new FileReader(profileFile));
				StringBuilder sb = new StringBuilder();
				while (true) {
					String readLine = bufferedReader.readLine();
					if (readLine == null) {
						break;
					}
					sb.append(readLine);
				}
				bufferedReader.close();
				Log.d(TAG, "the parse panel json str: " + sb);
				PANEL_MODEL = GsonUtils.Companion.getInstance().fromJson(sb.toString(), PanelModel.class);
				updateData();
			} catch (IOException e) {
				e.printStackTrace();
				if (bufferedReader != null) {
					try {
						bufferedReader.close();
					} catch (IOException ex) {
						ex.printStackTrace();
					}
				}
			}
		}
	}

	private void updateData() {
		if (PANEL_MODEL == null) {
			return;
		}
		panelSportMode = PANEL_MODEL.getProfilesList().get(sportMode);
		switch (panelSportMode.getTarget().get(0)) {
			case 0:
				targetValue.setText(panelSportMode.getTarget().get(1) + getString(R.string.device_profiles_setting_detail_target_time_title));
				break;
			case 1:
				targetValue.setText(panelSportMode.getTarget().get(1) + getString(R.string.device_profiles_setting_detail_target_distance_title));
				break;
			case 2:
				targetValue.setText(panelSportMode.getTarget().get(1) + getString(R.string.device_profiles_setting_detail_target_calories_title));
				break;
			case 3:
				targetValue.setText("");
				break;
		}
		autoPauseSwitch.setChecked(panelSportMode.getAutopause() == 1);
		switch (panelSportMode.getAutolap().get(1)) {
			case 0:
				autoLapValue.setText(panelSportMode.getAutolap().get(2) + getString(R.string.device_profiles_setting_detail_target_time_title));
				break;
			case 1:
				autoLapValue.setText(panelSportMode.getAutolap().get(2) + getString(R.string.device_profiles_setting_detail_target_distance_title));
				break;
			case 2:
				autoLapValue.setText(panelSportMode.getAutolap().get(2) + getString(R.string.device_profiles_setting_detail_target_calories_title));
				break;
			case 3:
				autoLapValue.setText(getString(R.string.device_profiles_setting_detail_lap_mode_location));
				break;
		}
		autoLapSwitch.setChecked(panelSportMode.getAutolap().get(0) == 1);
		switch (panelSportMode.getManuallap().get(1)) {
			case 0:
				manualLapValue.setText(getString(R.string.device_profiles_setting_detail_lap_mode_time));
				break;
			case 1:
				manualLapValue.setText(getString(R.string.device_profiles_setting_detail_lap_mode_distance));
				break;
			case 2:
				manualLapValue.setText(getString(R.string.device_profiles_setting_detail_lap_mode_calories));
				break;
			case 3:
				manualLapValue.setText(getString(R.string.device_profiles_setting_detail_lap_mode_location));
				break;
		}
		manualLapSwitch.setChecked(panelSportMode.getManuallap().get(0) == 1);
	}

	private void restoreContentToFileDefault() {
		List<PanelSportMode> tempList = Arrays.asList(GsonUtils.Companion.getInstance().fromJson(DEFAULT_PANEL_JSON_STR, PanelSportMode[].class));
		if (PANEL_MODEL != null) {
			PANEL_MODEL.getProfilesList().set(sportMode, tempList.get(sportMode));
		}
		saveContentToFile();
		updateData();
	}

	private void saveContentToFile() {
		String content = PanelModelToJsonUtil.toJson(PANEL_MODEL);
		CommonUtil.saveDeviceProfile(content, device_model, sn);
		CommonUtil.sendPanelsJsonFile(context, device_model, sn);
	}

	@Override public void onBackPressed() {
		saveContentToFile();
		super.onBackPressed();
	}

	@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_TARGET) {
			PANEL_MODEL = GsonUtils.Companion.getInstance().fromJson(data.getStringExtra("PANEL_MODEL"), PanelModel.class);
			updateData();
		}
	}
}